﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Company.Utility
{
    public class TConvert
    {
        /// <summary>
        /// 转换object为字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string toString(object value)
        {
            string res = "";
            if (value != null)
            {
                try
                {
                    res = System.Convert.ToString(value);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.Print(e.Message);
                }
            }
            return res;
        }

        /// <summary>
        /// 转换boolean为字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string toString(bool value)
        {
            string result = "";
            if (value)
            {
                result = "true";
            }
            else
            {
                result = "false";
            }
            return result;
        }

        /// <summary>
        /// 转换object为byte数组
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] toByteArray(object value)
        {
            if (value == null)
            {
                return new byte[0];
            }
            else
            {
                try
                {
                    return (byte[])(value);
                }
                catch
                {
                    return new byte[0];
                }
            }
        }

        public static string formatString(string sFormat, Int32 iValue)
        {
            return TConvert.formatString(sFormat, Convert.ToInt64(iValue));
        }

        public static string formatString(string sFormat, Int64 lValue)
        {
            string sRes = System.Convert.ToString(lValue);

            // 处理分隔符
            int iPos = sRes.Length - 1;
            string sText = "";
            for (int i = sFormat.Length - 1; i >= 0; i--)
            {
                char cCurValue = sFormat[i];
                if (cCurValue == '#'
                    || cCurValue >= '0' && cCurValue <= '9')
                {// # 或0-9
                    if (iPos >= 0)
                    {// 如果sRes还有内容
                        sText = sRes.Substring(iPos, 1) + sText;
                    }
                    else if (cCurValue == '#')
                    {// 如果当前是#,跳出循环
                        break;
                    }
                    else
                    {// 如果是0-9,则加上0-9
                        sText = System.Convert.ToString(cCurValue) + sText;
                    }
                    iPos--;
                }
                else
                {// 如果是其它格式字符
                    if (iPos >= 0)
                    {// 如果sRes还有效内容
                        sText = System.Convert.ToString(cCurValue) + sText;
                    }
                    else if (i > 0)
                    {
                        if (sFormat[i - 1] == '#')
                        {
                            break;
                        }
                        else
                        {
                            sText = System.Convert.ToString(cCurValue) + sText;
                        }
                    }
                    else
                    {
                        sText = System.Convert.ToString(cCurValue) + sText;
                    }
                }
            }
            return sText;
        }

        private static string formatDfString(string sFormat, Decimal dValue)
        {
            string sRes = System.Convert.ToString(dValue);
            int iPos = sRes.IndexOf('.');
            if (iPos >= 0)
            {
                sRes = sRes.Substring(iPos + 1, sRes.Length - iPos - 1);
            }
            else if (sRes == "0")
            {
                sRes = "";
            }

            string sText = "";
            iPos = 0;
            for (int i = 0; i < sFormat.Length; i++)
            {
                char cCurVal = sFormat[i];
                if (cCurVal == '#'
                    || (cCurVal >= '0'
                        && cCurVal <= '9'))
                {
                    if (iPos < sRes.Length)
                    {
                        sText += sRes.Substring(iPos, 1);
                    }
                    else if (cCurVal == '#')
                    {
                        break;
                    }
                    else
                    {
                        sText += System.Convert.ToString(cCurVal);
                    }
                    iPos++;
                }
                else
                {
                    if (iPos < sRes.Length)
                    {
                        sText += System.Convert.ToString(cCurVal);
                    }
                    else if (i + 1 < sFormat.Length)
                    {
                        if (sFormat[i + 1] == '#')
                        {
                            break;
                        }
                        else
                        {
                            sText += System.Convert.ToString(cCurVal);
                        }
                    }
                    else
                    {
                        sText += System.Convert.ToString(cCurVal);
                    }
                }
            }
            return sText;
        }

        public static string formatString(string sFormat, double dValue)
        {
            return TConvert.formatString(sFormat, Convert.ToDecimal(dValue));
        }

        public static string formatString(string sFormat, Decimal dValue)
        {
            string sFormatInt = "";
            string sFormatDf = "";

            bool bIsDf = false;
            for (int i = 0; i < sFormat.Length; i++)
            {
                if (!bIsDf)
                {
                    if (sFormat[i] != '.')
                    {
                        sFormatInt += System.Convert.ToString(sFormat[i]);
                    }
                    else
                    {
                        bIsDf = true;
                    }
                }
                else
                {
                    sFormatDf += System.Convert.ToString(sFormat[i]);
                }
            }

            long lValue = System.Convert.ToInt64(dValue);
            decimal dDfValue = dValue - lValue;

            string sText = TConvert.formatString(sFormatInt, lValue);
            string sText1 = TConvert.formatDfString(sFormatDf, dDfValue);
            if (sText1.Length > 0)
            {
                sText += "." + sText1;
            }

            return sText;
        }

        public static string formatDate(DateTime dtValue)
        {
            return TConvert.formatString("####", dtValue.Year)
                   + "-" + TConvert.formatString("00", dtValue.Month)
                   + "-" + TConvert.formatString("00", dtValue.Day);
        }

        public static string formatDateTime(DateTime dtValue)
        {
            return TConvert.formatDateTime19(dtValue);
        }

        public static string formatDateTime19(DateTime dtValue)
        {
            return TConvert.formatString("####", dtValue.Year)
                   + "-" + TConvert.formatString("00", dtValue.Month)
                   + "-" + TConvert.formatString("00", dtValue.Day)
                   + " " + TConvert.formatString("00", dtValue.Hour)
                   + ":" + TConvert.formatString("00", dtValue.Minute)
                   + ":" + TConvert.formatString("00", dtValue.Second);
        }

        public static string formatDateTime23(DateTime dtValue)
        {
            return TConvert.formatString("####", dtValue.Year)
                   + "-" + TConvert.formatString("00", dtValue.Month)
                   + "-" + TConvert.formatString("00", dtValue.Day)
                   + " " + TConvert.formatString("00", dtValue.Hour)
                   + ":" + TConvert.formatString("00", dtValue.Minute)
                   + ":" + TConvert.formatString("00", dtValue.Second)
                   + "." + TConvert.formatString("000", dtValue.Millisecond);
        }

        public static int toInt(string sValue)
        {
            try
            {
                return TConvert.toInt32(sValue);
            }
            catch
            {
                return 0;
            }
        }

        public static int toInt32(string sValue)
        {
            try
            {
                return Convert.ToInt32(TConvert.toInt64(sValue));
            }
            catch
            {
                return 0;
            }
        }

        public static Int64 toInt64(string sValue)
        {
            Int64 lRes = 0;

            bool bLessZero = false;
            try
            {
                string sText = sValue.Trim();
                for (int i = 0; i < sText.Length; i++)
                {
                    if (sText[i] >= '0' && sText[i] <= '9')
                    {
                        lRes = lRes * 10 + (Convert.ToInt32(sText[i]) - 48);
                    }
                    else if (i == 0 && sText[i] == '-')
                    {
                        bLessZero = true;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch
            {
            }
            if (bLessZero)
            {
                lRes = -lRes;
            }
            return lRes;
        }

        public static Int64 toInt64(object value)
        {
            Int64 result = 0;
            if (value != null)
            {
                try
                {
                    result = System.Convert.ToInt64(value);
                }
                catch
                {
                }
            }
            return result;
        }

        public static Int32 toInt32(object value)
        {
            Int32 iValue = 0;
            if (value != null)
            {
                try
                {
                    iValue = System.Convert.ToInt32(value);
                }
                catch
                {
                }
            }
            return iValue;
        }

        public static int toInt(object value)
        {
            return TConvert.toInt32(value);
        }

        public static double toDouble(string sValue)
        {
            try
            {
                return System.Convert.ToDouble(TConvert.toDecimal(sValue));
            }
            catch
            {
                return 0.0;
            }
        }

        public static Decimal toDecimal(string sValue)
        {
            Decimal dRes = 0;
            bool bLessZero = false;
            try
            {
                string sText = sValue.Trim();
                bool bIsDec = false;
                long lValue = 10;
                for (int i = 0; i < sText.Length; i++)
                {
                    if (!bIsDec)
                    {// 整数部分
                        if (sText[i] >= '0' && sText[i] <= '9')
                        {
                            dRes = dRes * 10 + (Convert.ToInt32(sText[i]) - 48);
                        }
                        else if (sText[i] == '.')
                        {
                            bIsDec = true;
                        }
                        else if (i == 0 && sText[i] == '-')
                        {
                            bLessZero = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (sText[i] >= '0' && sText[i] <= '9')
                        {
                            dRes = dRes + Convert.ToDecimal(Convert.ToInt32(sText[i]) - 48) / lValue;
                            lValue = lValue * 10;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            catch
            {
            }

            if (bLessZero)
            {
                dRes = -dRes;
            }
            return dRes;
        }

        public static DateTime toDate(string sValue)
        {
            int iYear = 0;
            int iMonth = 0;
            int iDay = 0;
            int iType = 0; // 0-年 1-月 2-日
            string sText = sValue.Trim();
            string sPart = "";
            for (int i = 0; iType < 3 && i < sValue.Length; i++)
            {
                if (sText[i] == '-'
                    || sText[i] == ' '
                    || i == sText.Length - 1)
                {
                    if (sText[i] >= '0' && sText[i] <= '9')
                    {
                        sPart = sPart + Convert.ToString(sText[i]);
                    }
                    else if (sText[i] == ' ')
                    {
                        iType = 2;
                    }

                    if (iType == 0)
                    {
                        iYear = TConvert.toInt(sPart);
                    }
                    else if (iType == 1)
                    {
                        iMonth = TConvert.toInt(sPart);
                    }
                    else if (iType == 2)
                    {
                        iDay = TConvert.toInt(sPart);
                    }
                    sPart = "";
                    iType++;
                }
                else if (sText[i] >= '0' && sText[i] <= '9')
                {
                    sPart = sPart + Convert.ToString(sText[i]);
                }
                else
                {
                    break;
                }
            }
            try
            {
                return new DateTime(iYear, iMonth, iDay, 0, 0, 0, 0);
            }
            catch
            {
            }
            return new DateTime();
        }

        //最后修改 贺小龙 2013年11月19日17:58:55 增加 ‘/’判断
        public static DateTime toDateTime(string sValue)
        {
            int iYear = 0;
            int iMonth = 0;
            int iDay = 0;
            int iHour = 0;
            int iMinute = 0;
            int iSecond = 0;
            int iMillSecond = 0;
            int iType = 0; // 0-年 1-月 2-日 3-小时 4-分钟 5-秒 6-毫秒
            string sText = sValue.Trim();
            string sPart = "";
            for (int i = 0; i < sValue.Length; i++)
            {
                if (sText[i] == '-'
                    || sText[i] == ' '
                    || sText[i] == ':'
                    || sText[i] == '.'
                    || sText[i] == '/'
                    || i == sText.Length - 1)
                {
                    if (sText[i] >= '0' && sText[i] <= '9')
                    {
                        sPart = sPart + Convert.ToString(sText[i]);
                    }
                    else if (sText[i] == ' ' && iType < 2)
                    {
                        iType = 2;
                    }
                    else if (sText[i] == '.' && iType < 5)
                    {
                        iType = 5;
                    }

                    if (iType == 0)
                    {
                        iYear = TConvert.toInt(sPart);
                    }
                    else if (iType == 1)
                    {
                        iMonth = TConvert.toInt(sPart);
                    }
                    else if (iType == 2)
                    {
                        iDay = TConvert.toInt(sPart);
                    }
                    else if (iType == 3)
                    {
                        iHour = TConvert.toInt(sPart);
                    }
                    else if (iType == 4)
                    {
                        iMinute = TConvert.toInt(sPart);
                    }
                    else if (iType == 5)
                    {
                        iSecond = TConvert.toInt(sPart);
                    }
                    else if (iType == 6)
                    {
                        iMillSecond = TConvert.toInt(sPart);
                    }
                    sPart = "";
                    if (sText[i] == ' ')
                    {
                        iType = 3;
                    }
                    else if (sText[i] == '.')
                    {
                        iType = 6;
                    }
                    else
                    {
                        iType++;
                    }
                }
                else if (sText[i] >= '0' && sText[i] <= '9')
                {
                    sPart = sPart + Convert.ToString(sText[i]);
                }
            }
            try
            {
                return new DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond, iMillSecond);
            }
            catch (Exception)
            {
                // ignored
            }
            return new DateTime();
        }

        public static bool toBoolean(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            else if (TString.strcmpi(value, "true") == 0)
            {
                return true;
            }
            else if (TString.strcmpi(value, "-1") == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public static Guid toGuid(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return Guid.Empty;
            }
            else
            {
                try
                {
                    return Guid.Parse(value);
                }
                catch (Exception)
                {
                    return Guid.Empty;
                }
            }
        }
        public static object toObject(string value, Type t)
        {
            return System.Convert.ChangeType(value, t);
        }

        /// <summary>
        /// 将中文数字转化为阿拉伯数字
        /// </summary>
        /// <param name="sNum"></param>
        /// <returns></returns>
        public static int toArabicNum(string sNum)
        {
            int iResult = 0;
            switch (sNum)
            {
                case "零"
                :
                    iResult = 0;
                    break;
                case "一"
                :
                    iResult = 1;
                    break;
                case "两"
                :
                    iResult = 2;
                    break;
                case "三"
                :
                    iResult = 3;
                    break;
                case "四"
                :
                    iResult = 4;
                    break;
                case "五"
                :
                    iResult = 5;
                    break;
                case "六"
                :
                    iResult = 6;
                    break;
                case "七"
                :
                    iResult = 7;
                    break;
                case "八"
                :
                    iResult = 8;
                    break;
                case "九"
                :
                    iResult = 9;
                    break;
            }
            return iResult;
        }

        /// <summary>
        /// 转换为金额
        /// <para>注意：商城中所有显示金额格式，如下：</para>
        /// <para>1.金额n，则显示n.00；</para>
        /// <para>2.金额n.00...1，则显示n.01；</para>
        /// 在显示时调用 ToString("0.00") 或者 ToString("f2")
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal toMoney(object value)
        {
            dynamic dotMoney = value.ToString();
            Regex regexMoney = new Regex(@"(?<money>\d+)"), regexIsMoney = new Regex(@"^\d+(\.\d+)?$");
            if (!regexIsMoney.IsMatch(dotMoney))
            {
                return 0.00m;
            }
            MatchCollection matches = regexMoney.Matches(dotMoney);
            var matchedCount = matches.Count;
            if (matchedCount == 1)
            {
                return decimal.Parse(matches[0].Value + ".00");
            }
            else if (matchedCount > 1)
            {
                dotMoney = matches[1].Value;
                if (dotMoney.Length == 1)
                {
                    return decimal.Parse(string.Concat(matches[0].Value, ".", dotMoney.PadRight(2, '0')));
                }
                else if (dotMoney.Length == 2)
                {
                    return decimal.Parse(value.ToString());
                }
                else if (dotMoney.Length > 2)
                {
                    var otherMoney = dotMoney.Substring(2, dotMoney.Length - 2);
                    dotMoney = dotMoney.Substring(0, 2);
                    long otherLongMoney = 0;
                    if (long.TryParse(otherMoney, out otherLongMoney) && otherLongMoney > 0)
                    {
                        dotMoney = decimal.Parse("0." + dotMoney) + 0.01m;
                    }
                    else
                    {
                        dotMoney = decimal.Parse("0." + dotMoney) + 0.00m;
                    }
                    dotMoney = decimal.Parse(matches[0].Value) + dotMoney;
                }
            }
            return dotMoney;
        }
    }
}
